package com.onlyphoto.onlymall.jpush;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import com.onlyphoto.onlymall.mvp.view.activity.SplashActivity;
import com.onlyphoto.onlymall.utils.LogUtil;
import com.onlyphoto.onlymall.utils.SchemeTool;

import org.json.JSONException;
import org.json.JSONObject;

import cn.jpush.android.api.JPushInterface;

/**
 * 自定义接收器
 * 
 * 如果不定义这个 Receiver，则：
 * 1) 默认用户会打开主界面
 * 2) 接收不到自定义消息
 */
public class MyReceiver extends BroadcastReceiver {
	private String TAG = "JPushReceiver";

	@Override
	public void onReceive(Context context, Intent intent) {
		Bundle bundle = intent.getExtras();
		if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
			String regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
			LogUtil.log(TAG, "[MyReceiver] 接收Registration Id : " + regId);
		} else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
			LogUtil.log(TAG, "收到了自定义消息。消息内容是：" + bundle.getString(JPushInterface.EXTRA_MESSAGE));
			// 自定义消息不会展示在通知栏，完全要开发者写代码去处理
		} else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
			LogUtil.log(TAG, "收到了通知");
			// 在这里可以做些统计，或者做些其他工作
		} else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
			LogUtil.log(TAG, "用户点击打开了通知");
			// 在这里可以自己写代码去定义用户点击后的行为
			String extra = bundle.getString(JPushInterface.EXTRA_EXTRA);
			JSONObject object = null;
			try {
				object = new JSONObject(extra);
			} catch (JSONException e) {
				e.printStackTrace();
			}
			Intent i = new Intent(context, SplashActivity.class);  //自定义打开的界面
			if (object != null) {
				if (SchemeTool.TAG_JUMP_H5.equals(object.optString("skip_code"))) {
					i.putExtra("jumpUri", object.optString("url"));
				} else {

					String params = SchemeTool.MyScheme + "://?skip_code=" + object.optString("skip_code");
					if (object.has("order_id")) {
						try {
							params = params + "&order_id=" + object.getString("order_id");
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}
					if (object.has("period_id")) {
						try {
							params = params + "&period_id=" + object.getString("period_id");
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}
					if (object.has("product_id")) {
						try {
							params = params + "&product_id=" + object.getString("product_id");
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}
					i.putExtra("jumpUri", params);
				}
			}

			i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			context.startActivity(i);
		} else {
			LogUtil.log(TAG, "Unhandled intent - " + intent.getAction());
		}
	}
}
